﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WebAPI存储过程多接口聚合.JWT;
using WebAPI存储过程多接口聚合.Models;

namespace WebAPI存储过程多接口聚合.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private static string BuildToken(IEnumerable<Claim> claims, JWTOptions options)
        {
            DateTime expires = DateTime.Now.AddSeconds(options.ExpireSeconds);
            byte[] keyBytes = Encoding.UTF8.GetBytes(options.SigningKey);
            var secKey = new SymmetricSecurityKey(keyBytes);
            var credentials = new SigningCredentials(secKey,
                SecurityAlgorithms.HmacSha256Signature);
            var tokenDescriptor = new JwtSecurityToken(expires: expires,
                signingCredentials: credentials, claims: claims);
            return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
        }

        [HttpPost]
        public async Task<IActionResult> Login2(LoginModel req,
                [FromServices] IOptions<JWTOptions> jwtOptions)
        {
            string userName = req.Account;
            string password = req.Password;

            //这里可以写账号密码的判断是否正确

            var claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, userName));
            claims.Add(new Claim(ClaimTypes.NameIdentifier, password));

            //for (int i = 0; i < 100; i++)
            //{
            //    claims.Add(new Claim(ClaimTypes.Role, i.ToString()));
            //}
            string jwtToken = BuildToken(claims, jwtOptions.Value);
            return Ok(jwtToken);
        }
    }
}
